//
//  ProgressImageView.swift
//  WeiBoSwift
//
//  Created by rong on 15/7/6.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit

class ProgressImageView: UIImageView {

  
    var progress: CGFloat = 0 {
        
        didSet {
            if progress > 0 {
                progressView.progress = progress
            }
        }
    }
    
    
    //[weak self] 表示闭包内的 self 是 弱引用
    //[unowned self] 表示闭包内部的 self 不做强引用
    
    private lazy var progressView: ProgressView = { [unowned self] in
    
        let v = ProgressView()
        self.addSubview(v)
        v.ff_Fill(self)
        
        return v
    }()
    
    
    
    //嵌套的私有类，仅供 ProgressImageView 使用
    private class ProgressView: UIView {
    
        //进度： 0.0 － 1.0
        var progress: CGFloat = 0{
        
            didSet {
                setNeedsDisplay()
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            
            backgroundColor = UIColor.clearColor()
        }

        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        
        // drawRect  参数中的 rect
        private override func drawRect(rect: CGRect) {
            
            if progress == 0 || progress == 1 {
                return
            }
            
            //0.准备
            let radius = min(rect.width, rect.height) * 0.5
            let center = CGPoint(x: rect.width*0.5, y: rect.height*0.5)
            let ovalRect = CGRectMake(center.x - radius, center.y - radius, radius * 2, radius * 2)
            
            //画圆
            let pathCircle = UIBezierPath(ovalInRect: ovalRect)
            UIColor(white: 1.0, alpha: 0.5).setFill()
            
            pathCircle.fill()
            
            let start = CGFloat(-M_PI_2)
            let end = CGFloat(2 * M_PI) * progress + start
            let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
            
            path.addLineToPoint(center)
            path.closePath()
            
            UIColor(white: 0.0, alpha: 0.5).setFill()
            path.fill()
        }
    
    }

}
